package com.itheima.filters;

import com.itheima.common.constants.SystemConstants;
import com.itheima.common.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class WemediaAuthorizeFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        /*
            1.获取请求对象
            2.获取响应对象
            3.白名单放行判断
              3.1 获取请求过来的url地址
              3.2 判断地址是否是后台的登录地址
         */
        ServerHttpRequest req = exchange.getRequest();
        ServerHttpResponse res = exchange.getResponse();
        String path = req.getURI().getPath();
        log.debug("请求的地址:{}",path);
        if(path.startsWith("/wemedia/login")){
            //是则放行
            log.debug("登录");
            return chain.filter(exchange);
        }
        log.debug("已登录，检查Token");
        //token校验
        //1. 获取token
        String token = req.getHeaders().getFirst("token");
        //2. 非空判断
        if(StringUtils.isNotEmpty(token)){
            //3. 验证token
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            if(null != claimsBody){
                //获取token中的登录用户id, 此时这里是自媒体网关，因此得到的id为WmUser表中的id
                Integer wmUserId = (Integer) claimsBody.get("id");
                //给请求头添加当前登录用户的id,方便下游处理获取
                req.mutate().header(SystemConstants.USER_HEADER_NAME, wmUserId.toString());
                //4. 验证通过则放行
                return chain.filter(exchange);
            }
            log.debug("token无效");
        }
        //5. 没有token，或验证没通过的，阻止请求。响应未登录
        res.setStatusCode(HttpStatus.UNAUTHORIZED);
        return res.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
